properties([
    parameters([
        [$class: 'ChoiceParameter',
         choiceType: 'PT_CHECKBOX',
         description: '请选择要合并的分支（可多选）',
         name: 'BRANCHES',
         script: [
             $class: 'GroovyScript',
             fallbackScript: [script: 'return ["ERROR"]'],
             script: [sandbox: false, script: '''
                def cmd = ["git", "ls-remote", "--heads", "http://oauth2:glpat-JhRsEkECWxjizfK_sMQG@gitlab.esaas.net/yinline/yinline.git"]
                def proc = cmd.execute()
                proc.waitFor()
                
                if (proc.exitValue() != 0) {
                    println "Git command failed: ${proc.err.text}"
                    return ["ERROR1"]
                } else {
                    def branches = proc.in.text.readLines().collect { line ->
                        def parts = line.tokenize("\\t")
                        parts.last().replaceAll("refs/heads/", "")
                    }
                    return branches 
                }
             ''']
         ]
        ]
    ])
])

pipeline {
    agent any
    environment {
        JAVA_HOME = "/usr/local/java17/jdk-17.0.1"
        MAVEN_HOME = "/usr/local/maven/apache-maven-3.9.4"
        PATH = "${JAVA_HOME}/bin:${MAVEN_HOME}/bin:$PATH"
        
        REPO_DIR = "yinline"
        DOCKER_COMPOSE_FILE = "docker-compose-yl-pro.yml"
        SERVICE_NAME = "yinline-upms yinline-intserv yinline-pay yinline-invoice yinline-contract yinline-property yinline-auth yinline-job"
    }
    stages {
        stage('Prepare Branch') {
            steps {
                script {
                    def workspace = env.WORKSPACE
                    def lastFile = "${workspace}/.last_release_branch"

                    // 读取上一次的临时分支信息
                    def lastBranch = null
                    def lastSelected = null
                    if (fileExists(lastFile)) {
                        def lines = readFile(lastFile).split("\n")
                        if (lines.size() >= 1) lastBranch = lines[0].trim()
                        if (lines.size() >= 2) lastSelected = lines[1].trim()
                    }

                    def currentSelected = params.BRANCHES.split(",").collect { it.trim() }.sort().join(",")

                    def releaseBranch
                    def needMerge = true
                    if (lastBranch && lastSelected == currentSelected) {
                        echo "分支未变化，复用上一次临时分支: ${lastBranch}"
                        releaseBranch = lastBranch
                        needMerge = false
                    } else {
                        releaseBranch = "release_${UUID.randomUUID().toString().replace('-', '')}"
                        echo "生成新的临时分支: ${releaseBranch}"
                    }
                    env.RELEASE_BRANCH = releaseBranch

                    withCredentials([usernamePassword(credentialsId: 'fc01ec98-9fda-498e-ba4e-84ac859c9748', usernameVariable: 'GIT_USER', passwordVariable: 'GIT_PASS')]) {

                        // 克隆 repo
                        if (!fileExists("${workspace}/${REPO_DIR}")) {
                            echo "repo 不存在，克隆仓库"
                            sh "git clone http://${GIT_USER}@gitlab.esaas.net/yinline/yinline.git ${REPO_DIR}"
                        }

                        if (needMerge) {
                            echo "需要重新合并，基于 main 初始化"

                            sh """
                                cd ${REPO_DIR}
                                git reset --hard
                                git clean -fdx
                                git fetch origin
                                git checkout main
                                git reset --hard origin/main
                            """

                            // 删除旧分支
                            if (lastBranch && lastSelected != currentSelected) {
                                echo "分支列表变化，删除上一次临时分支: ${lastBranch}"
                                sh """
                                    cd ${REPO_DIR}
                                    if git show-ref --verify --quiet refs/heads/${lastBranch}; then
                                        git branch -D ${lastBranch} || true
                                    fi
                                    if git ls-remote --exit-code --heads origin ${lastBranch}; then
                                        git push http://${GIT_USER}@gitlab.esaas.net/yinline/yinline.git --delete ${lastBranch} || true
                                    fi
                                """
                            }

                            // 创建新临时分支
                            sh """
                                cd ${REPO_DIR}
                                git checkout -B ${releaseBranch}
                                git config user.name "konghong"
                                git config user.email "wah1763751448@163.com"
                                git push http://${GIT_USER}@gitlab.esaas.net/yinline/yinline.git ${releaseBranch}
                            """

                            // 合并所选分支
                            def conflict = false
                            params.BRANCHES.split(",").each { b ->
                                echo "合并分支: ${b} -> ${releaseBranch}"
                                def status = sh(
                                    script: """
                                        cd ${REPO_DIR}
                                        git fetch origin ${b}
                                        git merge --no-ff origin/${b} -m "Merge branch ${b} into ${releaseBranch}"
                                    """,
                                    returnStatus: true
                                )
                                if (status != 0) {
                                    conflict = true
                                }
                            }

                            if (conflict) {
                                echo "⚠️ 检测到合并冲突！请在本地执行以下命令解决："
                                echo """
                                cd ${workspace}/${REPO_DIR}
                                git fetch origin
                                git checkout ${releaseBranch}
                                git pull
                                # 手动解决冲突
                                git add .
                                git commit
                                git push origin ${releaseBranch}
                                """
                                input message: """
                                合并冲突，请手工解决并推送到远程 ${releaseBranch} 分支后，
                                点击继续。
                                """, ok: "继续执行"
                            } else {
                                sh """
                                    cd ${REPO_DIR}
                                    git push origin ${releaseBranch}
                                """
                            }
                        } else {
                            echo "分支未变化，仅更新临时分支 ${releaseBranch}"

                            sh """
                                cd ${REPO_DIR}
                                git fetch origin
                                git checkout ${releaseBranch}
                                git reset --hard origin/${releaseBranch}
                                git clean -fdx
                            """
                        }
                    }

                    // 保存临时分支信息
                    writeFile file: lastFile, text: "${releaseBranch}\n${currentSelected}"
                }
            }
        }

        stage('Build with Maven') {
            steps {
                sh """
                    cd ${REPO_DIR}
                    mvn clean install -DskipTests
                """
            }
        }
        
        stage('Start Services') {
            steps {
                sh """
                    cd ${REPO_DIR}
                    docker-compose -f ${DOCKER_COMPOSE_FILE} build  ${SERVICE_NAME}
                    docker-compose -f ${DOCKER_COMPOSE_FILE} up -d --build ${SERVICE_NAME}
                    docker system prune -af
                """
            }
        }
        
        stage('Result') {
            steps {
                echo "✅ 已完成临时分支 ${env.RELEASE_BRANCH} 的合并和构建"
            }
        }
    }
}
